package com.jsu.exhibitor.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jsu.exhibitor.mapper.ExhibitorMapper;
import com.jsu.exhibitor.service.ExhibitorService;
import lombok.extern.slf4j.Slf4j;
import org.example.model.common.dtos.ResponseResult;
import org.example.model.common.enums.RedisCodeEnum;
import org.example.model.common.enums.WebHttpCodeEnum;
import org.example.model.exhibitor.dtos.ExhibitorDto;
import org.example.model.exhibitor.pojos.Exhibitor;
import org.example.model.information.pojo.News;
import org.example.model.user.pojo.PointDetail;
import org.example.utils.common.FileTools;
import org.example.utils.common.IdsUtils;
import org.example.utils.common.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ExhibitorServiceImpl extends ServiceImpl<ExhibitorMapper, Exhibitor> implements ExhibitorService {
    @Autowired
    private StringRedisTemplate redisCache;
    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 返回展商列表
     * @return exhibitor集合
     */
    @Override
    public ResponseResult getExhibitor() {
        //从redis中获取展商信息
        List<String> exhibitors = redisCache.opsForList().range(RedisCodeEnum.EXHIBITOR.getMsg(),0,-1);
        List<ExhibitorDto> exhibitorDtos = new ArrayList<>();
        if(exhibitors.isEmpty())
        {
            //从数据库中读取
            // 从数据库中读取 Exhibitor 集合
            exhibitorDtos = getBaseMapper().selectList(null)
                    .stream()
                    .map(exhibitor -> new ExhibitorDto(exhibitor.getPkId(), exhibitor.getLogoLink()))
                    .collect(Collectors.toList());
        }else{
            // 将 Exhibitor 集合转化为 ExhibitorDto 集合
            exhibitorDtos = exhibitors.stream()
                    .map(exhibitorJson -> {
                        try {
                            Exhibitor exhibitor = mapper.readValue(exhibitorJson, Exhibitor.class);
                            return new ExhibitorDto(exhibitor.getPkId(), exhibitor.getLogoLink());
                        } catch (JsonProcessingException ex) {
                            throw new RuntimeException(ex);
                        }
                    })
                    .collect(Collectors.toList());
        }
        if (exhibitorDtos.size()==0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"暂时还没有展商信息");
        }
        return ResponseResult.okResult(exhibitorDtos);
    }

    /**
     * 返回某一个展商的信息
     * @param id
     * @return exhibitor
     */
    @Override
    public ResponseResult getOneExhibitor(int id) {
        //从redis中获取信息
        String key = RedisCodeEnum.EXHIBITOR.getMsg()+id;
        log.info("key:{}",key);
        String json = redisCache.opsForValue().get(key);
        if(Objects.isNull(json)){
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"未找到该数据");
        }
//        Object parse = JSON.parse(json);
//        Exhibitor exhibitor=JSON.parseObject(parse.toString(), Exhibitor.class);
        Exhibitor exhibitor = null;
        try {
            exhibitor = mapper.readValue(json, Exhibitor.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        if(!Objects.isNull(exhibitor)){
            return ResponseResult.okResult(exhibitor);
        }
        //从数据库中获取
        exhibitor = getBaseMapper().selectById(id);
        if(Objects.isNull(exhibitor)){
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"没有该展商");
        }
        return ResponseResult.okResult(exhibitor);
    }

    /**
     * 新增展商信息
     * @param exhibitor
     * @return
     */
    @Transactional
    @Override
    public ResponseResult addExhibitor(Exhibitor exhibitor) {
        exhibitor.setPkId(Integer.valueOf(IdsUtils.creatCode()));
        String key = RedisCodeEnum.EXHIBITOR.getMsg()+exhibitor.getPkId();
        String json = null;
        try {
            json = mapper.writeValueAsString(exhibitor);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        redisCache.opsForValue().set(key,json);
        int count = getBaseMapper().insert(exhibitor);
        if (count<=0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"新增失败");
        }
        return ResponseResult.okResult(200,"新增成功");
    }

    /**
     * 删除展商
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteExhibitor(Integer id) {
        String key = RedisCodeEnum.EXHIBITOR.getMsg()+id;
        redisCache.opsForValue().getOperations().delete(key);
        int count = getBaseMapper().deleteById(id);
        if (count<=0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"删除失败");
        }
        return ResponseResult.okResult(200,"删除成功");
    }

    /**
     * 修改展商信息
     * @param exhibitor
     * @return
     */
    @Override
    public ResponseResult updateExhibitor(Exhibitor exhibitor) {
        String key = RedisCodeEnum.EXHIBITOR.getMsg()+exhibitor.getPkId();
        redisCache.opsForValue().getOperations().delete(key);
        String json = null;
        try {
            json = mapper.writeValueAsString(exhibitor);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        redisCache.opsForValue().set(key,json);
        int count = getBaseMapper().updateById(exhibitor);
        if (count<=0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"修改失败");
        }
        return ResponseResult.okResult(200,"修改成功");
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @Override
    public ResponseResult uploadExcel(MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"上传的文件不能为空");
        }
        try {
            File excelFile = File.createTempFile("temp", ".xlsx"); // 创建临时文件
            file.transferTo(excelFile); // 将上传的文件保存到临时文件
            List<Exhibitor> exhibitors = FileTools.readExcel(excelFile, Exhibitor.class); // 调用读取 Excel 方法
            //批量导入到数据库
            boolean success = saveBatch(exhibitors);
            //批量存储到redis中
            for (Exhibitor n:exhibitors) {
                String key = RedisCodeEnum.EXHIBITOR.getMsg()+n.getPkId();
                String json = mapper.writeValueAsString(n);
                redisCache.opsForValue().set(key,json);
            }
            if (success) {
                return ResponseResult.okResult(WebHttpCodeEnum.SUCCESS);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL);
        }
        return ResponseResult.errorResult(WebHttpCodeEnum.FAIL);
    }

    /**
     * 导出文件
     * @param fileName
     * @return
     */
    @Override
    public ResponseResult exportExcel(String fileName) {
        try {
            List<Exhibitor> exhibitors = getBaseMapper().selectList(null); // 获取要导出的数据集合
            if(exhibitors.isEmpty())
                return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"暂时没有数据");
            int count = FileTools.writeExcel(fileName, Exhibitor.class, exhibitors);// 调用写入 Excel 方法
            if(count>0)
                return ResponseResult.okResult(count);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"暂时没有数据");
    }

    /**
     * 模糊查询展商
     * @param keyword
     * @return
     */
    @Override
    public ResponseResult searchExhibitor(String keyword) {
        List<Exhibitor> exhibitors = getBaseMapper().searchExhibitorsByKeyword(keyword);
        if(exhibitors.isEmpty()){
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"没有该展商");
        }
        return ResponseResult.okResult(exhibitors);
    }

    /**
     * 批量删除展商
     * @param ids
     * @return
     */
    @Override
    public ResponseResult batchDeleteExhibitor(Integer[] ids) {
        for (Integer id:ids) {
            String key = RedisCodeEnum.EXHIBITOR.getMsg() + id;
            redisCache.opsForValue().getOperations().delete(key);
        }
        List<Integer> idList = ids.length>0? Arrays.asList(ids):new ArrayList<>();
        int count = getBaseMapper().deleteBatchIds(idList);
        if (count<=0) {
            return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"批量删除失败");
        }
        return ResponseResult.okResult(200,"批量删除成功");
    }

    /**
     * 获取所有展商
     * @return
     */
    @Override
    public ResponseResult getAllExhibitor() {
        List<Exhibitor> exhibitors = getBaseMapper().selectList(null);
        if (exhibitors.isEmpty()){
            return ResponseResult.errorResult(WebHttpCodeEnum.DATA_NOT_EXIST,"暂时没有数据");
        }
        return ResponseResult.okResult(exhibitors);
    }
}
